package com.ball.web;

import com.alibaba.fastjson.JSONObject;
import com.ball.entity.User;
import com.ball.service.UserService;
import com.ball.util.Mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/** 登录
 * Created by tengj on 2017/4/10.
 */
@Controller
public class LoginController extends  AbstractController{
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String, Object> map) {
        Map<String,Object> result =new HashMap<String,Object>();
        JSONObject json=new JSONObject(map);
        String username=json.getString("username");
        String password=json.getString("password");

        if(!(username.equals("")||password.equals(""))){
            logger.info(username+password);
            User user=userService.queryUserByUsername(json);
            if(StringUtils.isEmpty(user)){
                //账号未注册
                result.put("result","3");
            }
            else{
                if(user.getPassword().equals(password)){
                    //登入成功发邮件
                    try {
//                        Mail.sendMail(user.getMail());
                    }catch (Exception e){

                    }finally {
                        request.getSession().setAttribute("user",user);
                        result.put("result","1");
                        logger.info(result.toString());
                        return result;
                    }
                }else{
                    //密码错误
                    result.put("result","2");
                }

            }
        }else{
            logger.info("111");
            result.put("result","0");
        }

        return result;
    }
}
